using System;
using System.Threading;
using System.Configuration;

namespace MediaBackup
{
    // BrianSp: This class provides pre-canned entry point for a thread to continually push media through the processing
    // pipeline.
    public static class Pipeline
    {
        // BrianSp: This wrapper gets all the params from the config file.
        public static void RunFromAppConfig()
        {
            Settings settings = new Settings();
            settings.LoadFromAppSettings();

            string value = ConfigurationManager.AppSettings["Pipeline Delay Seconds"];
            int sleepSec = value == null ? 60 : int.Parse(value);

            Run(settings, sleepSec);
        }

        public static void Run(Settings settings, int sleepSec)
        {
            // BrianSp: The ProgressNext method will try to do whatever it has enough settings to do.  Because this method
            // is only intended to do post-download pipeline, we null out the settings that enable discovery and download.
            settings.TivoIpAddress = null;

            // BrianSp: If that didn't leave us with any work to do, then just return.
            if (settings.TivoIpAddress == null && settings.TivoDecrypter == null && settings.Transcoder == null)
                return;

            // BrianSp: Attempt to preauthenticate all the shares in the settings.
            settings.Authenticate();

            while (true)
            {
                try
                {
                    Tivo dl = new Tivo(settings);
                    Item.ProgressNext(settings.TivoDownloadRootPath, dl, settings);
                }
                catch (Exception e)
                {
                    Log.Write(e);
                }

                // BrianSp: Put in a delay just to be a little nicer to the server and network.  Also gives a period of time
                // after an operation completes where a shutdown can be invoked without cancelling a running operation.
                // A much better solution to safe shutdown is needed however, as it is impossible to accurately predict when
                // a download will complete.
                Thread.Sleep((int)TimeSpan.FromSeconds(sleepSec).TotalMilliseconds);
            }
        }
    }
}
